package com.goldze.mvvmhabit.ui.register;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.goldze.mvvmhabit.R;
import com.goldze.mvvmhabit.app.AppViewModelFactory;
import com.goldze.mvvmhabit.databinding.ActivityRegisterBinding;
import com.goldze.mvvmhabit.utils.GlideUtil;

import java.io.File;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.LogUtil;
import me.goldze.mvvmhabit.utils.Utils;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class RegisterActivity extends BaseActivity<ActivityRegisterBinding, RegisterViewModel> {

    private ArrayAdapter<String> adapter;


    //ActivityLoginBinding类是databinding框架自定生成的,对应activity_login.xml
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_register;
    }

    @Override
    public int initVariableId() {
        return com.goldze.mvvmhabit.BR.viewModel;
    }

    @Override
    public RegisterViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(RegisterViewModel.class);
    }

    @Override
    public void initData() {
        binding.rgModule.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbModuleNan:
                        LogUtil.e("选男");
                        viewModel.sex.set("男");
                        break;
                    case R.id.rbModuleNv:
                        viewModel.sex.set("女");
                        LogUtil.e("选女");
                        break;
                    default:
                }
            }
        });

        //头像点击事件
        binding.ivModuleHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openPhoto();
            }
        });

        binding.tvModuleClassName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.sModule.setVisibility(View.VISIBLE);
                binding.tvModuleClassName.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void initViewObservable() {
        /**
         * 头像赋值
         */
        viewModel.headUrl.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                GlideUtil.newCacheInstance(s,binding.ivModuleHead);
            }
        });


        viewModel.FBI_LIST.observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(@Nullable List<String> strings) {
                //第二步：为下拉列表定义一个适配器
                adapter = new ArrayAdapter<String>(RegisterActivity.this, android.R.layout.simple_spinner_item, strings);
                //第三步：设置下拉列表下拉时的菜单样式
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                //第四步：将适配器添加到下拉列表上
                binding.sModule.setAdapter(adapter);
                //第五步：添加监听器，为下拉列表设置事件的响应
                binding.sModule.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        /* 将所选spinnertext的值带入myTextView中*/
                        viewModel.setClassIdMethod(adapter.getItem(position));
                        binding.tvModuleClassName.setVisibility(View.VISIBLE);
                        binding.tvModuleClassName.setText(adapter.getItem(position));
                        /* 将 spinnertext 显示^*/
                        parent.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        binding.tvModuleClassName.setText("");
                        binding.tvModuleClassName.setVisibility(View.GONE);
                        binding.sModule.setVisibility(View.VISIBLE);
                        parent.setVisibility(View.VISIBLE);
                    }
                });
                //将spinnertext添加到OnTouchListener对内容选项触屏事件处理
                binding.sModule.setOnTouchListener(new Spinner.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        // TODO Auto-generated method stub
                        // 将mySpinner隐藏
                        v.setVisibility(View.INVISIBLE);
                        Log.i("spinner", "Spinner Touch事件被触发!");
                        return false;
                    }
                });
                //焦点改变事件处理
                binding.sModule.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() {
                    public void onFocusChange(View v, boolean hasFocus) {
                        // TODO Auto-generated method stub
                        v.setVisibility(View.VISIBLE);
                        Log.i("spinner", "Spinner FocusChange事件被触发！");
                    }
                });
            }
        });

    }


    /**
     * 打开相册
     */
    private void openPhoto() {
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, 3);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //相册完成,去裁剪 ,保存,上传
                case 3:
                    if (null != data) {
                        startPhotoZoom(data.getData());
                    }else{
                        LogUtil.e("data==null");
                    }
                    break;
                case 4:
                    GlideUtil.newCacheInstance(mS_imgUrl,binding.ivModuleHead);
                    Luban.with(Utils.getContext())
                            .load(mS_imgUrl)
                            .ignoreBy(100)
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {

                                }

                                @Override
                                public void onSuccess(File file) {
                                    viewModel.updateHeadImage(file);
                                }

                                @Override
                                public void onError(Throwable e) {
                                }
                            }).launch();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 调用系统裁剪
     *
     * @param uri
     */
    private String mS_imgUrl = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() + "img.jpg";

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        //裁剪后输出路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mS_imgUrl)));
        //输入图片路径
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("return-data", false);
        startActivityForResult(intent, 4);
    }

}
